package com.heima.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.heima.gateway.config.AuthProperties;
import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/*
全局过滤器，校验token是否有效
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Autowired
    private AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private AppJwtUtil jwtTool;

    /**
     * 执行过滤的方法
     * @param exchange 交换机，可以获取请求和响应对象
     * @param chain 过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    //1. 获取请求实例和响应实例
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2. 获取请求路径
        String path = request.getURI().getPath();
        //3. 判断是否可放行(判断当前请求路径是否是白名单,使用antPathMatcher进行匹配)
        long count = authProperties.getExcludePaths().stream().filter(x -> antPathMatcher.match(x, path)).count();
        if(count>0){
            return chain.filter(exchange);
        }
        //4. 获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        //5. 如果Token为空则响应401
        if(StrUtil.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //6. 解析Token
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            if (claims != null) {
                // 获取用户ID
                Long userId = claims.get("id", Long.class);
                //放行前设置用户ID
                request.mutate().header("user-info", userId.toString());
            }
            //7. 放行前设置用户id
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            //8. 如果Token解析失败则响应401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

    }

    /**
     * 过滤的执行的优先级，返回值越小优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
